<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/static/lib/layui-v2.8.3/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/static/index/css/public.css}" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
        .image-container {
            position: relative;
            display: inline-block;
        }

        .close-button {
            position: absolute;
            top: -6px;
            right: 3px;
            background-color: rgb(70 67 67 / 70%);
            color: white;
            font-size: 22px;
            width: 15px;
            height: 15px;
            padding: 4px;
            line-height: 15px;
            text-align: center;
            cursor: pointer;
            border-radius: 50px;
        }

        #upload-demo-preview img{
            margin-right: 5px;
            width: 90px;
            height: 90px;
        }

        .progressBox{
            position: absolute;
            width: 90px;
            height: 90px;
            top: 0;
            background-color: rgb(128 122 122 / 47%);
            display: none;
        }

        .progressBox > .layui-progress-big{
            top: 36px;
        }
    </style>
</head>
<body>
<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">房间类型</label>
        <div class="layui-input-block">
            <input type="text" name="type" lay-verify="required|type" lay-reqtext="房间类型不能为空" placeholder="请输入房间类型" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">价格</label>
        <div class="layui-input-block">
            <input type="text" name="price" lay-verify="required|price" lay-reqtext="价格不能为空" placeholder="请输入价格" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">介绍</label>
        <div class="layui-input-block">
            <textarea placeholder="请输入内容" name="description" lay-verify="required" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">图片</label>
        <div class="layui-input-block">
            <div class="layui-upload-drag" style="display: block;" id="ID-upload-demo-drag">
                <i class="layui-icon layui-icon-upload"></i>
                <div>点击上传，或将文件拖拽到此处</div>
            </div>
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 11px;">
                预览图：
                <div class="layui-upload-list" id="upload-demo-preview"></div>
            </blockquote>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button id="upload-btn" class="layui-btn layui-btn-normal  layui-hide">提交</button>
            <button class="layui-btn layui-btn-normal" id="form-submit"  lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
    </div>
</div>
<script>
    let ctx = '[[${#httpServletRequest.getContextPath()}]]';
</script>
<script th:src="@{/static/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script th:src="@{/static/lib/layui-v2.8.3/layui.js}" charset="utf-8"></script>
<script>
    layui.use(['form', 'upload', 'element'], function () {
        var form = layui.form,
            layer = layui.layer,
            upload = layui.upload,
            element = layui.element,
            $ = layui.$;

        let id;

        // 渲染
        let uploadListIns = upload.render({
            elem: '#ID-upload-demo-drag',
            url: ctx + '/upload', // 此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            auto: false, // 关闭自动上传
            bindAction: '#ID-upload-demo-size', // 不绑定默认的提交
            multiple: true, // 是否允许多文件上传。不支持 ie8/9
            files: {}, // 设置文件列表
            // number: 3, // 设置同时可上传的文件数量，一般配合 multiple 参数出现
            choose: function(obj){
                var that = this;
                var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列

                // 预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    // 渲染预览图
                    let {container, span} = renderPreviewElement(result, file.name, index);

                    // 删除  html元素 --> jquery 元素 $(html元素)
                    $(span).on('click', function(){
                        delete files[index]; // 删除对应的文件
                        container.remove(); // 删除表格行
                        // 清空 input file 值，以免删除后出现同名文件不可选
                        uploadListIns.config.elem.next()[0].value = '';
                    });
                    element.render('progress'); // 渲染新加的进度条组件
                });
            },
            allDone: function(obj){
                layer.msg('上传成功');
                console.log(obj.total); // 上传的文件总数
                console.log(obj.successful); // 上传成功的文件数
                console.log(obj.failed); // 上传失败的文件数
                // 刷新父页面表格
                parent.layui.table.reload('currentTableId');

                // 关闭弹出层
                layer.closeAll();


                var iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            },
            progress: function(n, elem, e, index){
                $(".progressBox" + index).css("display", "block");
                element.progress('filter-demo'+ index, n + '%'); // 可配合 layui 进度条元素使用
            },
            error: function(index, upload){
                console.log(index); // 当前文件的索引
                // upload(); 重新上传的方法
            }
        });

        // 自定义验证规则，如下以验证用户名和密码为例
        form.verify({
            // 函数写法
            // 参数 value 为表单的值；参数 item 为表单的 DOM 对象
            type: function(value, item){
                if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                    return '房间类型不能有特殊字符';
                }

                if(/^\d+$/.test(value)) return '房间类型不能全为数字';
                if (value.length < 2) return '房间类型长度不能小于2位';
            },
            // 数组写法。
            // 数组中两个成员值分别代表：[正则表达式、正则匹配不符时的提示文字]
            price: [/^\d+(,\d{3})*(\.\d{1,2})?$/, '请输入正确的价格']

        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            // 判断是否有图片 uploadListIns.config.files 是否是空对象
            if (!uploadListIns.config.files || Object.keys(uploadListIns.config.files).length == 0) {
                layer.msg('请上传图片', {icon: 2, time: 3000});
                return false;
            }
            // 显示loading
            let i = layer.load();
            data = data.field;

            if (data.price) {
                data.price = parseInt(data.price * 100);
            }

            // 发送请求
            fetch(ctx + '/roomType/add',{
                headers: {
                    'Content-Type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify(data)
            }).then(function (resp){
                return resp.json();
            }).then(function(json){
                if (json.code == 200){
                    console.log(json)
                    layer.close(i);
                    layer.alert('添加成功', {
                        title: '操作成功',
                    }, function () {
                        // 获取到房间类型的id
                        id = json.data;

                        // 上传图片
                        // 设置请求参数
                        uploadListIns.config.data.id = id;
                        // 上传
                        uploadListIns.upload();
                    });
                } else {
                    layer.msg(json.msg, {icon: 2, time: 1000});
                }
            }).catch(function (error) {
                layer.msg(error.msg, {icon: 2, time: 1000});
            });



            return false;
        });



        function renderPreviewElement(base64, fileName, index) {
            let container = document.createElement("div");
            container.className = "image-container";
            let html = `
                  <img src="${base64}" alt="${fileName}">
                    <div class="progressBox progressBox${index}">
                    <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="filter-demo${index}">
                        <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                    </div>
            `;
            container.innerHTML = html;
            let span = document.createElement("span");
            span.className = "close-button";
            span.innerHTML = "&times;";
            container.appendChild(span);
            // let div = document.createElement("div")
            // let img = document.createElement("img");
            // let span = document.createElement("span");
            // let progress = document.createElement("div");
            // let progressBox = document.createElement("div");
            // progressBox.classList.add("progressBox");
            // progressBox.classList.add("progressBox" + index);
            // div.className = "image-container";
            // img.src = base64;
            // img.alt = fileName;
            // img.title = fileName;
            // img.style.width = "90px";
            // img.style.height = "90px";
            // span.className = "close-button";
            // span.innerHTML = "&times;";
            // progress.className = "layui-progress layui-progress-big";
            // progress.setAttribute("lay-showPercent", "yes");
            // progress.setAttribute("lay-filter", "filter-demo" + index);
            // progress.innerHTML = '<div class="layui-progress-bar" lay-percent=""></div>';
            // progressBox.appendChild(progress);
            // div.appendChild(img);
            // div.appendChild(span);
            // div.appendChild(progressBox);
            $('#upload-demo-preview').append(container);
            return {container, span};
        }

    });
</script>
</body>
</html>